import type { AdListProps } from '../types/adList';
import { Ref, ComputedRef, ref, computed, unref, nextTick, watch } from 'vue';
import { getViewportOffset } from '@/utils/dom';
import { isBoolean, isNumber } from '@/utils/is';
import { useWindowSizeFn, onMountedOrActivated } from '@vben/hooks';
import { useModalContext } from '@/components/Modal';
import { useDebounceFn, promiseTimeout } from '@vueuse/core';
import {
  footerHeight as layoutFooterHeight,
  layoutMultipleHeadePlaceholderTime,
} from '@/settings/designSetting';

import { useRootSetting } from '@/hooks/setting/useRootSetting';

import { ScrollActionType } from '@/components/Container/index';

const { getShowFooter, getFullContent } = useRootSetting();

export function useListScroll(
  propsRef: ComputedRef<AdListProps>,
  wrapRef: Ref<HTMLElement | null>,
  formRef: Ref<ComponentRef>,
  listElRef: Ref<ComponentRef>,
  getDataSourceRef: ComputedRef<Recordable[]>,
) {
  const listHeightRef: Ref<Nullable<number | string>> = ref(167);
  const modalFn = useModalContext();

  // Greater than animation time 280
  const debounceRedoHeight = useDebounceFn(redoHeight, 100);

  const getCanResize = computed(() => {
    const { canResize } = unref(propsRef);
    return canResize || true;
  });

  const getCompactHeight = computed(() => {
    const { compactHeight } = unref(propsRef);
    return compactHeight || false;
  });

  watch(
    () => [unref(getCanResize), unref(getDataSourceRef)?.length, unref(getShowFooter)],
    () => {
      debounceRedoHeight();
    },
    {
      flush: 'post',
    },
  );

  watch(
    () => [unref(getFullContent)],
    async () => {
      // 等待动画结束后200毫秒
      await promiseTimeout(layoutMultipleHeadePlaceholderTime * 1000 + 200);
      debounceRedoHeight();
    },
    {
      flush: 'post',
    },
  );

  function redoHeight() {
    nextTick(() => {
      calcListHeight();
    });
  }

  function setHeight(height: number) {
    listHeightRef.value = height;
    //  Solve the problem of modal adaptive height calculation when the form is placed in the modal
    modalFn?.redoModalHeight?.();
  }

  // No need to repeat queries
  let paginationEl: HTMLElement | null;
  let footerEl: HTMLElement | null;
  let bodyEl: HTMLElement | null;

  async function calcListHeight() {
    const { resizeHeightOffset, pagination, maxHeight, isCanResizeParent, searchForm } =
      unref(propsRef);

    const list = unref(listElRef);
    if (!list) return;

    const listEl: Element = list.$el;
    if (!listEl) return;

    if (!bodyEl) {
      bodyEl = listEl.querySelector('.ant-spin-container');
      if (!bodyEl) return;
    }

    bodyEl!.style.height = 'unset';

    if (!unref(getCanResize)) return;

    await nextTick();
    // Add a delay to get the correct bottomIncludeBody paginationHeight footerHeight headerHeight

    // const headEl = listEl.querySelector('.ant-table-thead ');
    // if (!headEl) return;

    // Table height from bottom height-custom offset
    let paddingHeight = 32;
    // Pager height
    let paginationHeight = 2;
    if (!isBoolean(pagination)) {
      // 从 Dom 获取
      paginationEl = listEl.querySelector('.ant-pagination') as HTMLElement;
      if (paginationEl) {
        // 分页 margin-top
        // const paginationElMarginTop =
        //   parseInt(getComputedStyle(paginationEl)?.marginTop) || 10 + 24;
        const offsetHeight = paginationEl.offsetHeight;
        paginationHeight += offsetHeight || 0;
      } else {
        // TODO First fix 24
        paginationHeight += 24;
      }
    } else {
      paginationHeight = -8;
    }

    let footerHeight = 0;
    if (!isBoolean(pagination)) {
      if (!footerEl) {
        footerEl = listEl.querySelector('.ant-list-footer') as HTMLElement;
      } else {
        const offsetHeight = footerEl.offsetHeight;
        footerHeight += offsetHeight || 0;
      }
    }

    // let headerHeight = 0;
    // if (headEl) {
    //   headerHeight = (headEl as HTMLElement).offsetHeight;
    // }

    let bottomIncludeBody = 0;
    if (unref(wrapRef) && isCanResizeParent) {
      const listPadding = 12;
      const formMargin = 16;
      let paginationMargin = 10;
      const wrapHeight = unref(wrapRef)?.offsetHeight ?? 0;

      let formHeight = unref(formRef)?.$el.offsetHeight ?? 0;
      if (formHeight) {
        formHeight += formMargin;
      }
      if (isBoolean(pagination) && !pagination) {
        paginationMargin = 0;
      }
      if (isBoolean(searchForm) && !searchForm) {
        paddingHeight = 0;
      }

      const headerCellHeight =
        (listEl.querySelector('.ant-list-header') as HTMLElement)?.offsetHeight ?? 0;

      // console.log(wrapHeight - formHeight - headerCellHeight - listPadding - paginationMargin);
      bottomIncludeBody =
        wrapHeight - formHeight - headerCellHeight - listPadding - paginationMargin;
    } else {
      // List height from bottom
      const headEl = listEl.querySelector('.ant-list-header');
      if (headEl) {
        bottomIncludeBody =
          getViewportOffset(headEl).bottomIncludeBody -
          headEl.clientHeight -
          5 -
          (propsRef.value.heightOffset ?? 0);
      } else {
        bottomIncludeBody =
          getViewportOffset(listEl).bottomIncludeBody - 5 - (propsRef.value.heightOffset ?? 0);
      }
    }

    let height =
      bottomIncludeBody -
      (resizeHeightOffset || 0) -
      paddingHeight -
      paginationHeight -
      footerHeight -
      // headerHeight-
      (getShowFooter.value ? layoutFooterHeight : 0) -
      // 取高度ceil值
      1;
    height = (height > maxHeight! ? (maxHeight as number) : height) ?? height;
    if (unref(getCompactHeight)) {
      let listItemHeight = 0;
      const listItemEl = listEl.querySelector('.ant-spin-container');
      if (listItemEl) {
        listItemHeight = listItemEl.clientHeight;
        // console.log({ listItemHeight, height });
        height = height > listItemHeight ? listItemHeight : height;
      }
    }
    height = height - 9;
    setHeight(height);

    bodyEl!.style.height = `${height}px`;
  }
  useWindowSizeFn(calcListHeight, { wait: 280 });
  onMountedOrActivated(() => {
    calcListHeight();
    nextTick(() => {
      debounceRedoHeight();
    });
  });

  //设置滚动
  const scrollRef = ref<Nullable<ScrollActionType>>(null);
  const getScroll = computed(() => {
    const scroll = unref(scrollRef);
    if (!scroll) {
      throw new Error('scroll is Null');
    }
    return scroll;
  });
  function scrollTo(pos: number | 'top' | 'bottom') {
    const scroll = unref(getScroll);
    if (scroll) {
      if (isNumber(pos)) {
        scroll.scrollTo(pos);
      } else if (pos === 'top') {
        scroll.scrollTo(0);
      } else if (pos === 'bottom') {
        scroll.scrollBottom();
      }
    }
  }

  return { scrollRef, scrollTo, redoHeight };
}
